/**
 * 性能监控工具
 */

import { PERFORMANCE } from '@/constants'

// 性能指标接口
interface PerformanceMetrics {
  fcp?: number // First Contentful Paint
  lcp?: number // Largest Contentful Paint
  fid?: number // First Input Delay
  cls?: number // Cumulative Layout Shift
  ttfb?: number // Time to First Byte
}

class PerformanceMonitor {
  private metrics: PerformanceMetrics = {}
  private observers: PerformanceObserver[] = []

  constructor() {
    this.init()
  }

  /**
   * 初始化性能监控
   */
  private init() {
    if (typeof window === 'undefined') return

    // 监控 FCP
    this.observeFCP()
    
    // 监控 LCP
    this.observeLCP()
    
    // 监控 FID
    this.observeFID()
    
    // 监控 CLS
    this.observeCLS()
    
    // 监控 TTFB
    this.observeTTFB()
  }

  /**
   * 监控 First Contentful Paint
   */
  private observeFCP() {
    if (!('PerformanceObserver' in window)) return

    const observer = new PerformanceObserver((list) => {
      const entries = list.getEntries()
      const fcpEntry = entries.find(entry => entry.name === 'first-contentful-paint')
      
      if (fcpEntry) {
        this.metrics.fcp = fcpEntry.startTime
        this.checkThreshold('fcp', fcpEntry.startTime, PERFORMANCE.FCP_THRESHOLD)
      }
    })

    observer.observe({ entryTypes: ['paint'] })
    this.observers.push(observer)
  }

  /**
   * 监控 Largest Contentful Paint
   */
  private observeLCP() {
    if (!('PerformanceObserver' in window)) return

    const observer = new PerformanceObserver((list) => {
      const entries = list.getEntries()
      const lcpEntry = entries[entries.length - 1] // 取最后一个 LCP 条目
      
      if (lcpEntry) {
        this.metrics.lcp = lcpEntry.startTime
        this.checkThreshold('lcp', lcpEntry.startTime, PERFORMANCE.LCP_THRESHOLD)
      }
    })

    observer.observe({ entryTypes: ['largest-contentful-paint'] })
    this.observers.push(observer)
  }

  /**
   * 监控 First Input Delay
   */
  private observeFID() {
    if (!('PerformanceObserver' in window)) return

    const observer = new PerformanceObserver((list) => {
      const entries = list.getEntries()
      
      for (const entry of entries) {
        if (entry.processingStart && entry.startTime) {
          const fid = entry.processingStart - entry.startTime
          this.metrics.fid = fid
          this.checkThreshold('fid', fid, PERFORMANCE.FID_THRESHOLD)
        }
      }
    })

    observer.observe({ entryTypes: ['first-input'] })
    this.observers.push(observer)
  }

  /**
   * 监控 Cumulative Layout Shift
   */
  private observeCLS() {
    if (!('PerformanceObserver' in window)) return

    let clsValue = 0
    const observer = new PerformanceObserver((list) => {
      const entries = list.getEntries()
      
      for (const entry of entries) {
        const layoutShiftEntry = entry as PerformanceEntry & { hadRecentInput?: boolean; value?: number }
        if (!layoutShiftEntry.hadRecentInput) {
          clsValue += layoutShiftEntry.value || 0
        }
      }
      
      this.metrics.cls = clsValue
      this.checkThreshold('cls', clsValue, PERFORMANCE.CLS_THRESHOLD)
    })

    observer.observe({ entryTypes: ['layout-shift'] })
    this.observers.push(observer)
  }

  /**
   * 监控 Time to First Byte
   */
  private observeTTFB() {
    if (!('PerformanceObserver' in window)) return

    const observer = new PerformanceObserver((list) => {
      const entries = list.getEntries()
      const navigationEntry = entries[0] as PerformanceNavigationTiming
      
      if (navigationEntry) {
        const ttfb = navigationEntry.responseStart - navigationEntry.requestStart
        this.metrics.ttfb = ttfb
      }
    })

    observer.observe({ entryTypes: ['navigation'] })
    this.observers.push(observer)
  }

  /**
   * 检查性能阈值
   */
  private checkThreshold(metric: string, value: number, threshold: number) {
    if (value > threshold) {
      console.warn(`性能警告: ${metric} 值为 ${value}ms，超过阈值 ${threshold}ms`)
      
      // 这里可以发送到监控服务
      this.reportPerformanceIssue(metric, value, threshold)
    }
  }

  /**
   * 报告性能问题
   */
  private reportPerformanceIssue(metric: string, value: number, threshold: number) {
    // 发送到监控服务
    if (typeof window !== 'undefined' && (window as unknown as { gtag?: Function }).gtag) {
      const gtag = (window as unknown as { gtag: Function }).gtag
      gtag('event', 'performance_issue', {
        metric_name: metric,
        metric_value: value,
        threshold
      })
    }
  }

  /**
   * 获取性能指标
   */
  getMetrics(): PerformanceMetrics {
    return { ...this.metrics }
  }

  /**
   * 获取性能报告
   */
  getPerformanceReport() {
    const metrics = this.getMetrics()
    const report = {
      timestamp: Date.now(),
      url: window.location.href,
      userAgent: navigator.userAgent,
      metrics
    }

    return report
  }

  /**
   * 销毁监控器
   */
  destroy() {
    this.observers.forEach(observer => observer.disconnect())
    this.observers = []
  }
}

// 创建全局性能监控实例
export const performanceMonitor = new PerformanceMonitor()

// 导出性能监控工具函数
export const startPerformanceMonitoring = () => {
  // 性能监控已在构造函数中自动启动
  console.log('性能监控已启动')
}

export const getPerformanceMetrics = () => {
  return performanceMonitor.getMetrics()
}

export const getPerformanceReport = () => {
  return performanceMonitor.getPerformanceReport()
}

export const destroyPerformanceMonitoring = () => {
  performanceMonitor.destroy()
}